﻿// =============================================================================
// XPathDebugger And Examples MainWindow.xaml.cs
// Copyright (c) 2013 TNTTechnologies Inc.
// =============================================================================

#region

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Xml;
using System.Xml.XPath;

using Example;

using TNTTools;
using TNTTools.XML;

using XPathDebugger.CashFlowReports_Example;

#endregion

namespace XPathDebugger{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window{
        private DataSet dsTemp = new DataSet();

        public MainWindow(){
            this.InitializeComponent();
        }

        public DataView GridData{
            get{
                try{
                    return this.dsTemp.Tables[0].DefaultView;
                }
                catch{
                }
                return new DataView();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e){
            try{
                XmlDocument xmlDocument = new XmlDocument();

                xmlDocument.LoadXml(this.GetString(this.textBoxXml));
                XPathNavigator nav = xmlDocument.CreateNavigator();
                XPathNodeIterator iter = nav.Select(this.textBox1.Text);
                StringBuilder results = new StringBuilder();
                while (iter.MoveNext()){
                    results.Append(iter.Current.OuterXml);
                }
                this.SetString(this.richTextBoxResults, results.ToString());
                this.SetString(this.richTextErrors, "");
            }
            catch (Exception ex){
                this.SetString(this.richTextErrors, "");
                this.richTextErrors.AppendText(ex.ToString());
            }

            // The Text property on a TextRange object returns a string 
            // representing the plain text content of the TextRange. 
        }

        private void button2_Click(object sender, RoutedEventArgs e){
            //Update temp dataset
            this.dsTemp =
                XmlHelpers.ToDataSet(
                    XmlHelpers.GetElementString(this.textBox1.Text.ToString(), this.GetString(this.textBoxXml)));
        }

        private void textBoxXml_TextChanged_1(object sender, TextChangedEventArgs e){
            this.LoadXmlViewerControl(this.GetString(this.textBoxXml).Replace("\r\n", ""));
        }

        private void LoadXmlViewerControl(string xml){
            XmlDocument XMLdoc = new XmlDocument();
            try{
                XMLdoc.LoadXml(xml);
                this.viewer1.xmlDocument = XMLdoc;
                this.SetString(this.richTextErrors, "");
            }
            catch (Exception ex){
                this.SetString(this.richTextErrors, "");
                this.richTextErrors.AppendText(ex.ToString());
            }
        }

        /// <summary>
        ///     Positions the stream to 0 and reads in the string.
        ///     Warning: Do not reuse this code. see code comments.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public string GetStringFromStream(Stream stream){
            stream.Position = 0; // Warning, contract violation. Do not reuse this code.
            // Create a stream reader.
            StreamReader reader = new StreamReader(stream);
            // Just read to the end.
            return reader.ReadToEnd();
        }

        private void textBoxXmlRequest_TextChanged(object sender, TextChangedEventArgs e){
        }

        #region RichTextHelpers

        private string GetString(RichTextBox rtb){
            var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
            return textRange.Text;
        }

        private void SetString(RichTextBox rtb, string value){
            rtb.Document.Blocks.Clear();

            rtb.Document.Blocks.Add(new Paragraph(new Run(value.ToString())));
        }

        #endregion

        #region Serialization Examples

        /// <summary>
        ///     Serialization Example
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSerialize_Click(object sender, RoutedEventArgs e){
            this.Example1Serialization();
            this.Example2Serialization();
            PerformanceTests.SerializationPerformance(this.listboxPerformance);
            PerformanceTests.ReflectionPerformanceOfSetter(this.listboxPerformance);
            PerformanceTests.ReflectionPerformanceOfGetter(this.listboxPerformance);
        }

        /// <summary>
        ///     Serialization example, complex object
        /// </summary>
        private void Example2Serialization(){
            // Here we wil use a relatively complex object structure as an example of features,
            // but any object will do!
            CashFlowReport entity = new CashFlowReport(){ PorfolioName = "portfolioName" };
            IPodConnector connector = new IPodConnector(){ Version = "1.1a" };
            Screen screen = new Screen(){ Size = "4 inch" };
            Stereo stereo = new Stereo(){ Make = "alpine", Watts = "1000", };
            Car mycar = new Car(){ brake = "5 piston", wheel = "22", Stereo = stereo, IPodConnector = connector };

            for (int i = 0; i < 10; ++i){
                CashFlow cashFlow = new CashFlow(){
                    CashFlowValue = 1000000 * i,
                    FXRate = i,
                    CashFlowReportingCurrency = 46 + i,
                    PaymentDate = DateTime.Now,
                    PVCashFlow = 99999,
                    PVCashFlowReportingCurrency = 46 + i,
                    TradeCurrencyType = 13,
                    TradeName = "testName",
                    TradeType = "CAPFLOOR" + i.ToString()
                };

                entity.CashFlows.Add(cashFlow);
            }
            entity.MyCar = mycar;

            // Basic serialization example, raw with no attributes.
            StringBuilder XML1 = SerializerFacade.SerializeBasic(entity);

            // Attribute serialization example
            StringBuilder XMl2 = SerializerFacade.SerializeWithAttributeInformation(entity);

            // Serialize using stream.
            string xml3 = null;
            using (Stream stream = SerializerFacade.Serialize(entity, new MemoryStream())){
                xml3 = this.GetStringFromStream(stream);

                // test deserialization
                stream.Position = 0;
                CashFlowReport entityFromXml = SerializerFacade.Deserialize<CashFlowReport>(stream);
            }
            this.SetString(this.textBoxXml, xml3);
        }

        /// <summary>
        ///     Serialization Example - Simple objects
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Example1Serialization(){
            // Here we wil use a relatively complex object structure as an example of features,
            // but any object will do!

            IPodConnector connector = new IPodConnector(){ Version = "1.1a" };
            Screen screen = new Screen(){ Size = "4 inch" };
            Stereo stereo = new Stereo(){ Make = "alpine", Watts = "1000", };
            Car mycar = new Car(){ brake = "5 piston", wheel = "22", Stereo = stereo, IPodConnector = connector };

            // Basic serialization example, raw with no attributes.
            StringBuilder XML1 = SerializerFacade.SerializeBasic(mycar);
            Car entityFromXml = SerializerFacade.Deserialize<Car>(XML1.ToString());
        }

        #endregion
    }
}